package main

import (
	"database/sql"
	"errors"
	"fmt"
	"time"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

type User struct {
	ID           uint
	Name         string
	Email        *string
	Age          uint8
	Birthday     *time.Time
	MemberNumber sql.NullString
	ActivatedAt  sql.NullTime
	CreatedAt    time.Time
	UpdatedAt    time.Time
}

func main() {
	dsn := "root:root@tcp(192.168.4.111:3306)/mytest?charset=utf8mb4&parseTime=True&loc=Local"

	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		fmt.Println("err", err)
	}

	// 通过first查询单条数据
	var user User
	res := db.First(&user)
	fmt.Println("user", user)
	fmt.Println("res.Error", res.Error)
	fmt.Println("res.RowsAffected", res.RowsAffected)
	fmt.Println("<<==============================>>")

	// 添加检索条件
	// 通过主键查询
	res = db.First(&user, 10)
	fmt.Println("user", user) // 这里没有查询到数据, 所以user还是原来的值
	fmt.Println("res.Error", res.Error)
	// 判断是不是没找到
	fmt.Println("ErrRecordNotFound", errors.Is(res.Error, gorm.ErrRecordNotFound))
	fmt.Println("res.RowsAffected", res.RowsAffected)
	fmt.Println("<<==============================>>")

	var users []User
	res = db.Find(&users)
	fmt.Println("res.Error", res.Error)
	fmt.Println("res.RowsAffected", res.RowsAffected)
}
